<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 搜索与添加用户区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入搜索内容"
            v-model="queryInfo.query"
            clearable
            @clear="showCurrentUsers"
          >
            <el-button
              slot="append"
              @click="searchUser"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button @click="dialogVisible = !dialogVisible" type="primary"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table style="width: 100%" :data="usersList" border stripe>
        <el-table-column label="#" type="index"> </el-table-column>
        <el-table-column label="姓名" prop="username"> </el-table-column>
        <el-table-column label="邮箱" prop="email"> </el-table-column>
        <el-table-column label="电话" prop="mobile"> </el-table-column>
        <el-table-column label="角色" prop="role_name"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeState(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <!-- 用户列表操作区域 -->
        <el-table-column
          width="180px"
          label="操作"
          prop="mg_state"
          class="setBox"
        >
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUserDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="角色设置"
              placement="top"
              :enterable="false"
            >
              <!-- 角色设置按钮 -->
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 用户列表分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      @close="resetAddForm"
    >
      <el-form
        status-icon
        class="demo-ruleForm"
        label-width="70px"
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
      >
        <el-form-item label="姓名" prop="username">
          <el-input type="text" v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input type="text" v-model="addForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="text" v-model="addForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 重新编辑用户信息表单 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialogVisible"
      @close="resetEditForm"
    >
      <el-form
        status-icon
        class="demo-ruleForm"
        label-width="70px"
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
      >
        <el-form-item label="姓名" disabled>
          <el-input type="text" v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input type="text" v-model="editForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="text" v-model="editForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 职位分配对话框 -->
    <el-dialog
      title="职位分配"
      :visible.sync="setRolesDialogVisible"
      width="50%"
      @close="setRolesDialogClose"
    >
      <p>admin:{{ userInfo.username }}</p>
      <p>role:{{ userInfo.role_name }}</p>
      <el-select v-model="selectedRoleId" placeholder="请选择">
        <el-option
          v-for="item in rolesList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUserRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //邮箱验证规则
    let checkEmail = (rule, value, cb) => {
      let emailReg = /^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/
      if (emailReg.test(value)) cb()
      cb(new Error('请输入合法邮箱'))
    }
    //电话验证规则
    let checkMobile = (rule, value, cb) => {
      let mobileReg = /^1(3[0-9]|4[5,7]|5[0,1,2,3,5,6,7,8,9]|6[2,5,6,7]|7[0,1,7,8]|8[0-9]|9[1,8,9])\d{8}$/
      if (mobileReg.test(value)) cb()
      cb(new Error('请输入正确手机号码'))
    }
    return {
      //获取用户列表请求参数对象
      queryInfo: {
        //搜索用户关键字
        query: '',
        //当前的页数
        pagenum: 1,
        //每页条数
        pagesize: 2
      },
      usersList: [],
      total: 0,
      // 添加用户对话框显示/隐藏
      dialogVisible: false,
      // 编辑对话框显示/隐藏
      editDialogVisible: false,
      // 职位分配对话框显示/隐藏
      setRolesDialogVisible: false,
      //添加用户的信息对象
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //添加用户信息的校验规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' },
          { min: 3, max: 10, message: '请输入3-10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 15, message: '请输入6-15个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户电话', trigger: 'blur' },
          {
            validator: checkMobile,
            trigger: ['blur']
          }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            validator: checkEmail,
            trigger: ['blur']
          }
        ]
      },
      //编辑用户的信息对象
      editForm: {},
      //编辑用户信息的验证规则
      editFormRules: {
        mobile: [
          { required: true, message: '请输入用户电话', trigger: 'blur' },
          {
            validator: checkMobile,
            trigger: ['blur']
          }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            validator: checkEmail,
            trigger: ['blur']
          }
        ]
      },
      //职位分配用户的信息对象
      userInfo: {},
      //职位列表
      rolesList: [],
      selectedRoleId: ''
    }
  },
  created() {
    this.getUsersList()
  },
  methods: {
    //获取用户列表数据
    async getUsersList() {
      let res = await this.$api.getUsers({ params: this.queryInfo })
      let {
        data: {
          data: { pagenum, total, users },
          meta
        }
      } = res
      if (meta.status !== 200) return
      this.usersList = users
      this.rolesList = users
      this.pagenum = pagenum
      this.total = total
    },
    //监听切换每页条数(pagesize的变化,pageSize每页条数
    handleSizeChange(pageSize) {
      if (this.queryInfo.pagesize !== pageSize) {
        this.queryInfo.pagesize = pageSize
        //当每页条数变化,需要重新请求数据
        this.getUsersList()
      }
    },
    //监听当前页码变化,currentPage当前页
    handleCurrentChange(currentPage) {
      this.queryInfo.pagenum = currentPage
      //当页码发生变化,需要重新请求数据
      this.getUsersList()
    },
    //监听用户状态修改
    async changeState(userInfo) {
      //拿到新的状态发送请求
      let {
        data: { data, meta }
      } = await this.$api.changeUserState(userInfo)
      if (meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('用户状态更新失败')
      }
      this.$message.success('用户状态更新成功')
    },
    //实现关键字搜索用户功能
    searchUser() {
      this.getUsersList()
    },
    //实现清空关键字后展示所有数据的功能
    showCurrentUsers() {
      this.getUsersList()
    },
    //重置添加用户对话框的关闭事件
    resetAddForm(refName) {
      //对话框关闭就将表单重置
      this.$refs['addFormRef'].resetFields()
    },
    //添加用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          let res = await this.$api.addUser(this.addForm)
          let {
            data: { data, meta }
          } = res
          if (meta.status === 201) {
            this.$message.success('添加用户成功')
            this.dialogVisible = !this.dialogVisible
            this.getUsersList()
          } else {
            this.$message.error('添加用户失败')
          }
        }
      })
    },
    //编辑用户
    async editUserDialog(id) {
      let {
        data: { data, meta }
      } = await this.$api.getOneUser(id)
      if (meta.status === 200) {
        this.editForm = data
      } else {
        this.$message.error('查询用户信息失败')
      }
      this.editDialogVisible = true
    },
    //重置编辑用户对话框
    resetEditForm() {
      this.$refs.editFormRef.resetFields()
    },
    //修改用户信息完成后提交
    editUserInfo() {
      //先对编辑后的表单预验证
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          let {
            data: { _, meta }
          } = await this.$api.finishEditUser(this.editForm.id, {
            mobile: this.editForm.mobile,
            email: this.editForm.email
          })
          if (meta.status === 200) {
            this.$message.success('用户信息修改成功')
            this.editDialogVisible = false
            this.getUsersList()
          } else {
            this.$message.error('用户信息修改失败')
          }
        }
      })
    },
    //根据ID删除用户信息
    async deleteUser(id) {
      let res = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(() => this.$message.info('已取消删除'))
      if (res === 'confirm') {
        let {
          data: { _, meta }
        } = await this.$api.deleteOneUser(id)
        console.log()
        if (meta.status === 200) {
          this.$message.success('删除成功')
          this.getUsersList()
        } else {
          this.$message.error('删除失败')
        }
      }
    },
    //职位设置对话框
    async setRoles(userInfo) {
      this.userInfo = userInfo
      let {
        data: { data, meta }
      } = await this.$api.getRolesData()
      if (meta.status !== 200) return this.$message.error('获取职位列表失败')
      this.rolesList = data
      this.setRolesDialogVisible = true
    },
    //职位设置好后,保存到数据库
    async saveUserRoles() {
      let {
        data: { _, meta }
      } = await this.$api.setUserRoles(this.userInfo.id, {
        rid: this.selectedRoleId
      })
      if (meta.status === 200) {
        this.$message.success('职位设置成功')
        this.getUsersList()
        this.setRolesDialogVisible = false
      }else if (meta.msg === '不允许修改admin账户') {
        this.$message.error('不允许修改admin账户')
      }
    },
    //监听职位设置对话框关闭事件
    setRolesDialogClose() {
      this.userInfo = ''
      this.selectedRoleId = ''
    }
  }
}
</script>

<style lang="less" scoped>
.el-breadcrumb {
  height: 20px;
  line-height: 20px;
  padding-bottom: 10px;
  margin-bottom: 10px;
  border-bottom: 1px solid #ccc;
}
.el-table {
  margin-top: 15px;
}
.el-pagination {
  margin-top: 15px;
}
</style>
